<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"chentianming11.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":{"enable":true,"onlypost":false,"loadingImg":"/uploads/loading.gif"},"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="在《spring-boot项目整合Retrofit最佳实践，最优雅的HTTP客户端工具！》这篇文章中，我们知道了retrofit-spring-boot-starter的使用方式。本篇文章继续继续介绍retrofit-spring-boot-starter的实现原理，从零开始介绍如何在spring-boot项目中基于Retrofit实现自己的轻量级http调用工具。  项目源码：retrofit-">
<meta property="og:type" content="article">
<meta property="og:title" content="手把手教你基于Retrofit实现自己的轻量级http调用工具">
<meta property="og:url" content="https://chentianming11.github.io/posts/1979374763/index.html">
<meta property="og:site_name" content="伍六七">
<meta property="og:description" content="在《spring-boot项目整合Retrofit最佳实践，最优雅的HTTP客户端工具！》这篇文章中，我们知道了retrofit-spring-boot-starter的使用方式。本篇文章继续继续介绍retrofit-spring-boot-starter的实现原理，从零开始介绍如何在spring-boot项目中基于Retrofit实现自己的轻量级http调用工具。  项目源码：retrofit-">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://chentianming11.github.io/images/retrofit/retrofit-uml.png">
<meta property="article:published_time" content="2020-07-16T09:00:05.000Z">
<meta property="article:modified_time" content="2020-08-05T00:44:00.972Z">
<meta property="article:author" content="陈添明">
<meta property="article:tag" content="http">
<meta property="article:tag" content="spring">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://chentianming11.github.io/images/retrofit/retrofit-uml.png">

<link rel="canonical" href="https://chentianming11.github.io/posts/1979374763/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>手把手教你基于Retrofit实现自己的轻量级http调用工具 | 伍六七</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">伍六七</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">一起学Java</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">6</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">3</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">17</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/chentianming11" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://chentianming11.github.io/posts/1979374763/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="陈添明">
      <meta itemprop="description" content="一个爱看国漫的程序猿">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="伍六七">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          手把手教你基于Retrofit实现自己的轻量级http调用工具
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-07-16 17:00:05" itemprop="dateCreated datePublished" datetime="2020-07-16T17:00:05+08:00">2020-07-16</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-08-05 08:44:00" itemprop="dateModified" datetime="2020-08-05T08:44:00+08:00">2020-08-05</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE/" itemprop="url" rel="index"><span itemprop="name">开源项目</span></a>
                </span>
            </span>

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/posts/1979374763/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/posts/1979374763/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>6.3k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>16 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>在《<a href="https://juejin.im/post/5f14d81cf265da22ee7fbff0" target="_blank" rel="noopener">spring-boot项目整合Retrofit最佳实践，最优雅的HTTP客户端工具！</a>》这篇文章中，我们知道了<code>retrofit-spring-boot-starter</code>的使用方式。本篇文章继续继续介绍<code>retrofit-spring-boot-starter</code>的实现原理，从零开始介绍<strong>如何在spring-boot项目中基于Retrofit实现自己的轻量级http调用工具</strong>。</p>
<blockquote>
<p>项目源码：<a href="https://github.com/LianjiaTech/retrofit-spring-boot-starter" target="_blank" rel="noopener">retrofit-spring-boot-starter</a></p>
</blockquote>
<a id="more"></a>

<h2 id="确定实现思路"><a href="#确定实现思路" class="headerlink" title="确定实现思路"></a>确定实现思路</h2><p>我们首先直接看一下使用<code>retrofit</code>原始API是如何发起一个http请求的。</p>
<ol>
<li><p>定义接口</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">GitHubService</span> </span>&#123;</span><br><span class="line"><span class="meta">@GET</span>(<span class="string">"users/&#123;user&#125;/repos"</span>)</span><br><span class="line">Call&lt;List&lt;Repo&gt;&gt; listRepos(<span class="meta">@Path</span>(<span class="string">"user"</span>) String user);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>创建接口代理对象</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Retrofit retrofit = <span class="keyword">new</span> Retrofit.Builder()</span><br><span class="line">    .baseUrl(<span class="string">"https://api.github.com/"</span>)</span><br><span class="line">    .build();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 实际业务场景构建Retrofit比这复杂多了，这里最简单化处理</span></span><br><span class="line"></span><br><span class="line">GitHubService service = retrofit.create(GitHubService<span class="class">.<span class="keyword">class</span>)</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>发起请求</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Call&lt;List&lt;Repo&gt;&gt; repos = service.listRepos(<span class="string">"octocat"</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>可以看到，<code>Retrofit</code>本身已经很好的支持了通过接口发起<code>htp</code>请求。但是如果我们项目每一个业务代码都要写上面的样板代码，会非常的繁琐。有没有一种方式<strong>让用户只关注接口定义，其它事情全部交给框架自动处理</strong>？这个时候我们可能会联想到<code>spring-boot</code>项目下使用<code>Mybatis</code>，用户只需要定义<code>Mapper</code>接口和书写<code>sql</code>即可，完全不用管与<code>JDBC</code>的交互细节。与之类似，<strong>我们最终也要实现让用户只需要定义<code>HttpService</code>接口，不用管其他底层实现细节</strong>。</p>
<h2 id="相关知识介绍"><a href="#相关知识介绍" class="headerlink" title="相关知识介绍"></a>相关知识介绍</h2><p>为了方便后面的介绍，我们先得了解一下几个相关知识点。</p>
<h3 id="spring容器初始化"><a href="#spring容器初始化" class="headerlink" title="spring容器初始化"></a>spring容器初始化</h3><p>我们首先要简单了解一下<code>spring</code>容器初始化。简单来讲，<code>spring</code>容器初始化主要包含以下2个步骤：</p>
<ol>
<li><strong>注册Bean定义</strong>：扫描并解析<strong>配置文件</strong>或者<strong>某些注解</strong>得到Bean属性(包括<code>beanName</code>、<code>beanClassName</code>、<code>scope</code>、<code>isSingleton</code>等等)，然后基于这个<code>bean</code>属性创建<code>BeanDefinition</code>对象，最后将其注册到<code>BeanDefinitionRegistry</code>中。</li>
<li><strong>创建Bean实例</strong>：根据<code>BeanDefinitionRegistry</code>里面的<code>BeanDefinition</code>信息，创建Bean实例，并将实例对象保存到<code>spring</code>容器中，创建的方式包括反射创建、工厂方法创建和工厂Bean(<code>FactoryBean</code>)创建等等。</li>
</ol>
<p>当然，实际的<code>spring</code>容器初始化比这复杂的多，考虑到这块不是本文的重点，暂时这么理解就行。</p>
<h3 id="Retrofit对象简介"><a href="#Retrofit对象简介" class="headerlink" title="Retrofit对象简介"></a><code>Retrofit</code>对象简介</h3><p>我们已经知道使用<code>Retrofit</code>对象可以创建接口代理对象，接下来看一下<code>Retrofit</code>的UML类图(只列出了我们关注的依赖)：</p>
<p><img data-src="https://chentianming11.github.io/images/retrofit/retrofit-uml.png" alt="retrofit-uml"></p>
<p>通过分析UML类图，我们可以发现，构建<code>Retrofit</code>对象的时候，可以注入以下4个属性：</p>
<ol>
<li><code>HttpUrl</code>：<code>http</code>请求的<code>baseUrl</code>。</li>
<li><code>CallAdapter</code>：将<code>Call&lt;T&gt;</code>适配为接口方法返回值类型。</li>
<li><code>Converter</code>：将<code>@Body</code>标记的方法参数序列化为请求体数据；将响应体数据反序列化为响应对象。</li>
<li><code>OkHttpClient</code>：底层发送<code>http</code>请求的客户端对象。</li>
</ol>
<p>而构建<code>OkHttpClient</code>对象的时候，可以注入<code>Interceptor</code>(请求拦截器)和<code>ConnectionPool</code>(连接池)属性。</p>
<p>因此<strong>为了构建<code>Retrofit</code>对象，我们要先创建<code>HttpUrl</code>、<code>CallAdapter</code>、<code>Converter</code>和<code>OkHttpClient</code>；而要构建<code>OkHttpClient</code>对象就得先创建<code>Interceptor</code>和<code>ConnectionPool</code></strong>。</p>
<h2 id="实现详解"><a href="#实现详解" class="headerlink" title="实现详解"></a>实现详解</h2><h3 id="注册Bean定义"><a href="#注册Bean定义" class="headerlink" title="注册Bean定义"></a>注册Bean定义</h3><p>为了实现将<code>HttpService</code>接口代理对象完全交由<code>spring</code>容器管理，首先就得将<code>HttpService</code>接口扫描并注册到<code>BeanDefinitionRegistry</code>中。<code>spring</code>提供了<code>ImportBeanDefinitionRegistrar</code>接口，支持了自定义注册<code>BeanDefinition</code>的功能。因此我们先定义<code>RetrofitClientRegistrar</code>类用来实现上述功能。具体实现如下：</p>
<ol>
<li><p><code>RetrofitClientRegistrar</code></p>
<p> <code>RetrofitClientRegistrar</code>从<code>@RetrofitScan</code>注解中提取出要扫描的基础包路径之后，将具体的扫描注册逻辑交给了<code>ClassPathRetrofitClientScanner</code>处理。</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RetrofitClientRegistrar</span> <span class="keyword">implements</span> <span class="title">ImportBeanDefinitionRegistrar</span>, <span class="title">ResourceLoaderAware</span>, <span class="title">BeanClassLoaderAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 省略其它代码</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinitions</span><span class="params">(AnnotationMetadata metadata, BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">        AnnotationAttributes attributes = AnnotationAttributes</span><br><span class="line">                .fromMap(metadata.getAnnotationAttributes(RetrofitScan<span class="class">.<span class="keyword">class</span>.<span class="title">getName</span>()))</span>;</span><br><span class="line">        <span class="comment">// 扫描指定路径下@RetrofitClient注解的接口，并注册到BeanDefinitionRegistry</span></span><br><span class="line">        <span class="comment">// 真正的扫描注册逻辑交给了ClassPathRetrofitClientScanner执行</span></span><br><span class="line">        ClassPathRetrofitClientScanner scanner = <span class="keyword">new</span> ClassPathRetrofitClientScanner(registry, classLoader);</span><br><span class="line">        <span class="keyword">if</span> (resourceLoader != <span class="keyword">null</span>) &#123;</span><br><span class="line">            scanner.setResourceLoader(resourceLoader);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//指定扫描的基础包</span></span><br><span class="line">        String[] basePackages = getPackagesToScan(attributes);</span><br><span class="line">        scanner.registerFilters();</span><br><span class="line">        <span class="comment">// 扫描并注册到BeanDefinition</span></span><br><span class="line">        scanner.doScan(basePackages);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>ClassPathRetrofitClientScanner</code></p>
<p> <code>ClassPathRetrofitClientScanner</code>继承了<code>ClassPathBeanDefinitionScanner</code>，这是Spring提供的类路径下<code>BeanDefinition</code>的扫描器。需要注意的一点是：<strong><code>BeanDefinition</code>的<code>beanClass</code>属性全部设置为了<code>RetrofitFactoryBean.class</code>，同时将接口自身的类型传递到了<code>RetrofitFactoryBean</code>的<code>retrofitInterface</code>属性中</strong>。这说明，最终创建Bean实例是通过<code>RetrofitFactoryBean</code>来完成的。</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassPathRetrofitClientScanner</span> <span class="keyword">extends</span> <span class="title">ClassPathBeanDefinitionScanner</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 省略其它代码</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">processBeanDefinitions</span><span class="params">(Set&lt;BeanDefinitionHolder&gt; beanDefinitions)</span> </span>&#123;</span><br><span class="line">        GenericBeanDefinition definition;</span><br><span class="line">        <span class="keyword">for</span> (BeanDefinitionHolder holder : beanDefinitions) &#123;</span><br><span class="line">            definition = (GenericBeanDefinition) holder.getBeanDefinition();</span><br><span class="line">            <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                logger.debug(<span class="string">"Creating RetrofitClientBean with name '"</span> + holder.getBeanName()</span><br><span class="line">                        + <span class="string">"' and '"</span> + definition.getBeanClassName() + <span class="string">"' Interface"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            definition.getConstructorArgumentValues().addGenericArgumentValue(Objects.requireNonNull(definition.getBeanClassName()));</span><br><span class="line">            <span class="comment">// beanClass全部设置为RetrofitFactoryBean</span></span><br><span class="line">            definition.setBeanClass(RetrofitFactoryBean<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>这样，我们就完成了<strong>扫描指定路径下带有<code>@RetrofitClient</code>注解的接口，并将其注册到<code>BeanDefinitionRegistry</code>的功能了</strong>。</p>
<blockquote>
<p><code>@RetrofitClient</code>注解要标识在<code>HttpService</code>的接口上！<code>@RetrofitScan</code>指定了要扫描的包路径。具体可看考源码。</p>
</blockquote>
<h3 id="创建Bean实例"><a href="#创建Bean实例" class="headerlink" title="创建Bean实例"></a>创建Bean实例</h3><p>上面已经说了创建Bean实例实际上是通过<code>RetrofitFactoryBean</code>实现的。具体就是实现<code>FactoryBean&lt;T&gt;</code>接口，然后重写<code>getObject()</code>方法来完成<strong>创建接口Bean实例</strong>的逻辑。并且，我们也已经知道通过<code>Retrofit</code>对象能够生成接口代理对象。因此<code>getObject()</code>方法的核心就是构建<code>Retrofit</code>对象，并基于此生成<code>http</code>接口代理对象。</p>
<ol>
<li><p>配置项和<code>@RetrofitClient</code><br>为了更加灵活的构建<code>Retrofit</code>对象，我们可以通过配置项以及<code>@RetrofitClient</code>注解属性传递一些动态参数信息。<code>@RetrofitClient</code>包含的属性如下：</p>
<ol>
<li><code>baseUrl</code>：用来创建<code>Retrofit</code>的<code>HttpUrl</code>，表示该接口下所有请求都适用的<code>基础url</code>。</li>
<li><code>poolName</code>：该接口下请求使用的连接池的名称，决定了<code>ConnectionPool</code>对象的取值。</li>
<li><code>connectTimeoutMs/readTimeoutMs/writeTimeoutMs</code>：用于构建<code>OkHttpClien</code>t对象的超时时间设置。</li>
<li><code>logLevel/logStrategy</code>：配置该接口下请求的日志打印级别和日志打印策略，可用来创建日志打印拦截器<code>Interceptor</code>。</li>
</ol>
</li>
<li><p><code>RetrofitFactoryBean</code><br> <code>RetrofitFactoryBean</code>实现逻辑非常复杂，概括起来主要包含以下几点：</p>
<ol>
<li><p>通过配置项数据以及<code>@RetrofitClient</code>注解数据完成了<code>Retrofit</code>对象的构建。</p>
</li>
<li><p>每一个<code>HttpService</code>接口就会构建一个<code>Retrofit</code>对象，每一个<code>Retrofit</code>对象就会构建对应的<code>OkHttpClient</code>对象。</p>
</li>
<li><p>可扩展的注解式拦截器是通过<code>InterceptMark</code>注解标记实现的，路径拦截匹配是通过<code>BasePathMatchInterceptor</code>实现的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RetrofitFactoryBean</span>&lt;<span class="title">T</span>&gt; <span class="keyword">implements</span> <span class="title">FactoryBean</span>&lt;<span class="title">T</span>&gt;, <span class="title">EnvironmentAware</span>, <span class="title">ApplicationContextAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 省略其它代码</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">RetrofitFactoryBean</span><span class="params">(Class&lt;T&gt; retrofitInterface)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.retrofitInterface = retrofitInterface;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getObject</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 接口校验</span></span><br><span class="line">        checkRetrofitInterface(retrofitInterface);</span><br><span class="line">        <span class="comment">// 构建Retrofit对象</span></span><br><span class="line">        Retrofit retrofit = getRetrofit(retrofitInterface);</span><br><span class="line">        <span class="comment">// 基于Retrofit创建接口代理对象</span></span><br><span class="line">        <span class="keyword">return</span> retrofit.create(retrofitInterface);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 获取OkHttpClient实例，一个接口接口对应一个OkHttpClient</span></span><br><span class="line"><span class="comment">    *</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> retrofitClientInterfaceClass retrofitClient接口类</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span> OkHttpClient实例</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">synchronized</span> OkHttpClient <span class="title">getOkHttpClient</span><span class="params">(Class&lt;?&gt; retrofitClientInterfaceClass)</span> <span class="keyword">throws</span> IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException </span>&#123;</span><br><span class="line">        <span class="comment">// 基于各种条件构建OkHttpClient</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 获取Retrofit实例，一个retrofitClient接口对应一个Retrofit实例</span></span><br><span class="line"><span class="comment">    *</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> retrofitClientInterfaceClass retrofitClient接口类</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span> Retrofit实例</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">synchronized</span> Retrofit <span class="title">getRetrofit</span><span class="params">(Class&lt;?&gt; retrofitClientInterfaceClass)</span> <span class="keyword">throws</span> InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException </span>&#123;</span><br><span class="line">        <span class="comment">// 构建retrofit</span></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
</li>
</ol>
<p>这样，我们就完成了创建<code>HttpService</code>Bean实例的功能了。在使用的时候直接注入<code>HttpService</code>，然后调用其方法就能发送对应的<code>http</code>请求。</p>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>总的来说，在spring-boot项目中基于Retrofit实现自己的轻量级http调用工具的核心只有两点：第一是注册<code>HttpService</code>接口的<code>BeanDefinition</code>，第二就是构建<code>Retrofit</code>来创建<code>HttpService</code>的代理对象。如需了解更多细节，建议直接查看<a href="https://github.com/LianjiaTech/retrofit-spring-boot-starter" target="_blank" rel="noopener">retrofit-spring-boot-starter源码</a>。</p>
<blockquote>
<p>原创不易，觉得文章写得不错的小伙伴，点个赞👍 鼓励一下吧~</p>
</blockquote>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/http/" rel="tag"># http</a>
              <a href="/tags/spring/" rel="tag"># spring</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/2257172027/" rel="prev" title="spring-boot项目整合Retrofit最佳实践，最优雅的HTTP客户端工具！">
      <i class="fa fa-chevron-left"></i> spring-boot项目整合Retrofit最佳实践，最优雅的HTTP客户端工具！
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/293834368/" rel="next" title="面试中的老大难-mysql事务和锁，一次性讲清楚！">
      面试中的老大难-mysql事务和锁，一次性讲清楚！ <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#确定实现思路"><span class="nav-number">1.</span> <span class="nav-text">确定实现思路</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#相关知识介绍"><span class="nav-number">2.</span> <span class="nav-text">相关知识介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#spring容器初始化"><span class="nav-number">2.1.</span> <span class="nav-text">spring容器初始化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Retrofit对象简介"><span class="nav-number">2.2.</span> <span class="nav-text">Retrofit对象简介</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现详解"><span class="nav-number">3.</span> <span class="nav-text">实现详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#注册Bean定义"><span class="nav-number">3.1.</span> <span class="nav-text">注册Bean定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建Bean实例"><span class="nav-number">3.2.</span> <span class="nav-text">创建Bean实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number">4.</span> <span class="nav-text">结语</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="陈添明"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">陈添明</p>
  <div class="site-description" itemprop="description">一个爱看国漫的程序猿</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">17</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">陈添明</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">156k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">6:30</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-ribbon@1/canvas-ribbon.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-pjax@0/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  
  <script src="//cdn.jsdelivr.net/npm/quicklink@1/dist/quicklink.umd.js"></script>
  <script>
      window.addEventListener('load', () => {
      quicklink({
        timeout : 3000,
        priority: true,
        ignores : [uri => uri.includes('#'),uri => uri === 'https://chentianming11.github.io/posts/1979374763/',]
      });
      });
  </script>


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'SoPxUkme2aynTULaNuIc5TIq-gzGzoHsz',
      appKey     : '4TDP7SMCbgDKTOGGUtpIeA0H',
      placeholder: "留下点足迹吧~",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

    </div>
</body>
</html>
